package com.ktjiaoyu.ktmall.dao.impl;

import com.ktjiaoyu.ktmall.dao.BaseDao;
import com.ktjiaoyu.ktmall.dao.CategoryDao;
import com.ktjiaoyu.ktmall.dao.ProductDao;
import com.ktjiaoyu.ktmall.entity.Product;

import java.sql.ResultSet;
import java.sql.SQLDataException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDaoImpl extends BaseDao implements ProductDao {
    @Override
    public List<Product> findList(String title, Long categoryId, int page, int pageSize) {
        StringBuilder sql = new StringBuilder("SELECT`id`, `title`, `subtitle`, `category_id`, `category_path`, `brand`, `main_image`, `images`, `description`, `price`, `original_price`, `stock`, `sales`, `status`, `is_deleted`, `create_time`, `update_time` FROM kt_product WHERE is_deleted=0");
        List<Object> params = new ArrayList<>();
        if(title!=null&&!title.isEmpty()){
            sql.append(" AND title LIKE ?");
            params.add("%"+title+"%");
        }
        if (categoryId!=null){
            sql.append(" AND FIND_IN_SET(?,category_path");
            params.add(categoryId);
        }
        sql.append(" ORDER BY create_time DESC LIMIT ?,?");
        params.add((page-1)*pageSize);
        params.add(pageSize);
        try{
            return executeQuery(sql.toString(),rs->{
                List<Product> list = new ArrayList<>();
                try{
                    while (rs.next()) {

                        list.add(extractProduct(rs));
                    }
                }catch (SQLException e){
                    e.printStackTrace();
                }
                return list;
            },params.toArray());
        }catch (SQLException e){
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    private Product extractProduct(ResultSet rs) throws SQLException {
        Product product = new Product();
        product.setId(rs.getLong("id"));
        product.setTitle(rs.getString("title"));
        product.setSubtitle(rs.getString("subtitle"));
        product.setCategoryId(rs.getLong("category_id"));
        product.setCategoryPath(rs.getString("category_path"));
        product.setBrand(rs.getString("brand"));
        product.setMainImage(rs.getString("main_image"));
        product.setImages(rs.getString("images"));
        product.setDescription(rs.getString("description"));
        product.setPrice(rs.getDouble("price"));
        product.setOriginalPrice(rs.getDouble("original_price"));
        product.setStock(rs.getInt("stock"));
        product.setSales(rs.getInt("sales"));
        product.setStatus(rs.getInt("status"));
        product.setIsDeleted(rs.getInt("is_deleted"));
        product.setCreateTime(rs.getTime("create_time"));
        product.setUpdateTime(rs.getTime("update_time"));
        return product;
    }

    @Override
    public int count(String title, Long categoryId) {
        StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM kt_product WHERE is_deleted=0");
        List<Object> params = new ArrayList<>();
        if (title!=null&&!title.isEmpty()){
            sql.append(" AND title LIKE ?");
            params.add("%"+title+"%");
        }
        if (categoryId!=null){
            sql.append(" AND FIND_IN_SET(?,category_path)");
            params.add(categoryId);
        }
        try{
            List<Integer> result = executeQuery(sql.toString(),rs->{
                List<Integer> I = new ArrayList<>();
                try{
                    if (rs.next()){
                        I.add(rs.getInt(1));
                    }
                }catch (SQLException e){
                    e.printStackTrace();
                }
                return I;
            }, params.toArray());
            return  result.isEmpty()?0:result.get(0);
        }catch (SQLException e){
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Product findById(Long id) {
        String sql="SELECT * FROM kt_product WHERE id=? AND is_deleted=0";
        try{
            List<Product> list = executeQuery(sql,rs->{
                List<Product> I=new ArrayList<>();
                try {
                    while (rs.next()){
                        I.add(extractProduct(rs));
                    }
                }catch (SQLException e){
                    e.printStackTrace();
                }
                return I;
            },id);
            return list.isEmpty()?null:list.get(0);
        }catch (SQLException e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int insert(Product product) {
        String sql = "INSERT INTO `kt_product`( `title`, `subtitle`, `category_id`, `category_path`, `brand`, `main_image`, `images`, `description`, `price`, `original_price`, `stock`, `sales`, `status`, `is_deleted`, `create_time`, `update_time`) VALUES (?, ?, ?, ?, ?, ?, ?, ?,?, ?,?, ?,?, 0 , NOW(), NOW())";
        try{
            return executeUpdate(sql,product.getTitle(),product.getSubtitle(),product.getCategoryId(),product.getCategoryPath(),product.getBrand(),product.getMainImage(),product.getImages(),product.getDescription(),product.getPrice(),product.getOriginalPrice(),product.getStock(),product.getSales()!=null?product.getSales():0,product.getStatus());
        }catch (SQLException e){
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int update(Product product) {
       StringBuilder sql = new StringBuilder("UPDATE kt_product SET ");
       List<Object> params=new ArrayList<>();
       if(product.getTitle()!=null){
           sql.append(" title=?,");
           params.add(product.getTitle());
       }
       if (product.getSubtitle()!=null){
           sql.append(" subtitle=?,");
           params.add(product.getSubtitle());
       }
       if (product.getCategoryId()!=null){
           sql.append(" category_id=?,");
           params.add(product.getCategoryId());
       }
       if (product.getCategoryPath()!=null){
           sql.append(" category_path=?,");
           params.add(product.getCategoryPath());
       }
       if (product.getBrand()!=null){
           sql.append(" brand=?,");
           params.add(product.getBrand());
       }
       if (product.getMainImage()!=null){
           sql.append(" main_image=?,");
           params.add(product.getMainImage());
       }
       if (product.getImages()!=null){
           sql.append(" images=?,");
           params.add(product.getImages());
       }
       if (product.getDescription()!=null){
           sql.append(" description=?,");
           params.add(product.getDescription());
       }
       if (product.getPrice()!=null){
           sql.append(" price=?,");
           params.add(product.getPrice());
       }
       if (product.getOriginalPrice()!=null){
           sql.append(" original_price=?,");
           params.add(product.getOriginalPrice());
       }
       if (product.getStock()!=null){
           sql.append(" stock=?,");
           params.add(product.getStock());
       }
       if (product.getSales()!=null){
           sql.append(" sales=?,");
           params.add(product.getSales());
       }
       if (product.getStatus()!=null){
           sql.append(" status=?,");
           params.add(product.getStatus());
       }
       sql.append("update_time=NOW() WHERE id=?");
       params.add(product.getId());
       try {
           return executeUpdate(sql.toString(),params.toArray());
       }catch (SQLException e){
           e.printStackTrace();
           return -1;
       }
    }

    @Override
    public int delete(Long id) {
        String sql = "UPDATE kt_product SET is_deleted=1,update_time=NOW() WHERE id=?";
        try{
            return executeUpdate(sql,id);
        }catch (SQLException e){
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int updateStatus(Long id, Integer status) {
        String sql="UPDATE kt_product SET status=?,update_time=NOW() WHERE id=?";
        try{
            return executeUpdate(sql,status,id);
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }
}
